package org.zjx.net.download;

import java.io.File;
import java.util.List;

public class DownManager {

    public interface DownloadListCallback {
        void onProgress(int progress);  // 下载进度
        void onSuccess();      // 下载成功
        void onFailure(Exception e);    // 下载失败
    }

    private File cacheFile;
    private List<String> urls;
    private int maxSize;
    private int overSize;
    private DownloadListCallback listCallback;

    private int downOverSize = 0;

    private boolean fail = false;

    public DownManager(File cacheFile, int maxSize, List<String> urls,DownloadListCallback listCallback) {
        this.cacheFile = cacheFile;
        this.maxSize = maxSize;
        this.overSize = maxSize - urls.size();
        this.urls = urls;
        this.listCallback = listCallback;
        summary();
    }

    public void download(){
        if (urls == null || urls.isEmpty()) return;
        for (int i = 0; i < urls.size(); i++) {
            String url = urls.get(i);
            url = url.replace("http:", "https:");
            File file = new File(cacheFile,getFilenameFromUrl(url));

            DownloadUtils.downloadFile(url, file, new DownloadUtils.DownloadCallback() {
                @Override
                public void onProgress(int progress) {

                }

                @Override
                public void onSuccess(File file) {
                    downOverSize++;
                    summary();
                }

                @Override
                public void onFailure(Exception e) {

                    listCallback.onFailure(e);
                }
            });
        }
    }

    public void summary(){
        int progress = ((overSize + downOverSize) * 100) / maxSize;
        listCallback.onProgress(progress);
        if (downOverSize >= maxSize){
            listCallback.onSuccess();
        }
    }

    private static String getFilenameFromUrl(String url) {
        return url.substring(url.lastIndexOf("/") + 1); // 通过URL获取文件名
    }
}
